﻿
using Gnivc.CarDealership.Api.Application.Abstractions.Repositories;
using Gnivc.CarDealership.Api.Infrastructure.Persistence;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System.Threading;

namespace Gnivc.CarDealership.Api.BackgroundServices;

public class ReservationCleanupService : BackgroundService
{
    private readonly IServiceScopeFactory _serviceScopeFactory;

    public ReservationCleanupService(IServiceScopeFactory serviceScopeFactory)
    {
        _serviceScopeFactory = serviceScopeFactory;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            var now = DateTime.UtcNow;
            // Будет отрабатывать каждый день в 00:05
            var nextRunTime = now.Date
                .AddDays(1)
                .AddHours(0)
                .AddMinutes(5);
            var delay = nextRunTime - now;

            if (delay > TimeSpan.Zero)
                await Task.Delay(delay, stoppingToken);

            await ReservationCleanup(stoppingToken);
        }
    }

    private async Task ReservationCleanup(CancellationToken stoppingToken)
    {
        using var scope = _serviceScopeFactory.CreateScope();
        var context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
        var now = DateTime.UtcNow;

        var expiredReservations = context.Reservations
            .Where(r => !r.IsDeleted && r.EndDate < now)
            .ToList();

        foreach (var reservation in expiredReservations)
            reservation.IsDeleted = true;

        context.Reservations.UpdateRange(expiredReservations);
        await context.SaveChangesAsync(stoppingToken);
    }
}
